const express = require('express');
const multer = require('multer');
const cors = require('cors');
const fs = require('fs');
const path = require('path');


const app = express();
app.use(cors());


// 指定资源上传目录与文件名
const storage = multer.diskStorage({
  // 修改并指定文件目录
  destination(req, file, cb) {
    try {
      fs.mkdirSync(path.join(process.cwd(), 'my-uploads'));
    }catch(e) {}
    cb(null, path.join(process.cwd(), 'my-uploads'))
  },
  // 修改并指定文件名
  filename(req, file, cb) {
    const fileSuffix = file.originalname.split('.')
    const uniqueSuffix = `${Date.now()}.${fileSuffix[1]}`
    cb(null, uniqueSuffix)
  }
});
const upload = multer({ storage });


// 单个字段(单个、多个文件)
app.post('/uploadSingleFile', upload.single('aaa'), (req, res, next) => {
  console.log(req.file, req.body);
});
app.post('/uploadMultipleFile', upload.array('bbb', 2), (req, res, next) => {
  console.log(req.file, req.body);
}, (err, req, res, next) => {
  if (err instanceof multer.MulterError && err.code === 'LIMIT_UNEXPECTED_FILE') {
    res.status(400).end('Too many files uploaded');
  }
});


// 多个字段多个文件
app.post('/uploadMultipleFileField', upload.fields([
  { name: 'aaa', maxCount: 3 },
  { name: 'bbb', maxCount: 2 }
]), (req, res, next) => {
  console.log(req.file, req.body);
});


// 任意数量字段任意数量文件
app.post('/uploadMultipleFileUnknown', upload.any(), (req, res, next) => {
  console.log(req.file, req.body);
});


app.listen(3333);
